package com.qianqian.service.config;

import com.qianqian.service.exception.BusinessException;
import com.qianqian.service.model.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class ErrorControllerAdvice {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Response errorHandler(Exception ex) {
        StackTraceElement[] st = ex.getStackTrace();
        String errorMessage = "[类:" + st[0].getClassName() + "]调用"
                + st[0].getMethodName() + "时在第" + st[0].getLineNumber()
                + "行代码处发生异常!异常类型:" + ex.getClass().getName();
        ex.printStackTrace();
        logger.error(errorMessage);
        return Response.fail(10000,errorMessage);
    }

    /**
     * 拦截捕捉自定义异常 BusinessException.class
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public Response BusinessExceptionHandler(BusinessException ex) {
        logger.error(ex.getCode()+":"+ex.getMsg());
        return Response.fail(ex.getCode(),ex.getMsg());
    }
}
